<script setup>
import {reactive} from 'vue';
const props = defineProps({
    servePort:String,
    serveUrl:String,
    cell:Object,
    form:Object,
    cellIndex:String,
    cellMap:Object
})
const state = reactive({
    options:[]
})
const handleChange = (value) => {
    props.form[props.cell.__vModel__] = value;
}
const findItemByV = (data,v,label,value,children) => {
    for (let i = 0; i < data.length; i++) {
		let item = data[i];
		
		if (item[value] === v) {
			return item[label];
		} else {
			// item.children 不等于 undefined && item.children.length 大于 0 时
			if (item[children] && item[children].length > 0) {
				let res = findItemByV(item[children],v,label,value,children);
				// 当 res = undefined 时不会进入判断中
                // 也就是不会return
				if (res) return res;
			}
		}
	}
};
function parseTemplate(templateStr,cellMap) {
    console.log(templateStr,'templateStr')
    console.log(cellMap,'cellMap')
    return templateStr.replace(/\$\{(\w+)\}/g, (match, cellIndex) => {
        const cell = cellMap[props.cellIndex]
        // 空值处理三部曲
        if (!cell) return 'null';                   // 情况1：单元格不存在
        if (cell.value === '') return '""';          // 情况2：显式空字符串
        if (cell.value == null) return 'null';      // 情况3：null/undefined
        
        // 常规类型处理
        return typeof cell.value === 'string' 
        ? `"${cell.value}"` 
        : cell.value;
    });
}
function refactorTreeFields(tree, fieldMap = {
  id: 'newId',
  name: 'newName',
  chiildren: 'children' // 修正拼写错误
}) {
  return tree.map(node => {
    // 创建新节点
    const newNode = {
      ...Object.fromEntries(
        Object.entries(node)
          .filter(([key]) => !Object.keys(fieldMap).includes(key))
          .map(([k, v]) => [k, v])
      )
    };

    // 处理字段重命名
    Object.entries(fieldMap).forEach(([oldKey, newKey]) => {
      if (node[oldKey] !== undefined) {
        newNode[newKey] = node[oldKey];
      }
    });

    // 递归处理子节点
    if (node.chiildren?.length) {
      newNode[fieldMap.chiildren] = refactorTreeFields(node.chiildren, fieldMap);
    }

    return newNode;
  });
}
const getName = (v)=>{
    let str = "";
    let label = props.conf.props.props.label;
    let value = props.conf.props.props.value;
    let children = props.conf.props.props.children;
    return findItemByV(state.options,v,label,value,children)
    
}
const getOptsByApi = async ()=>{
    let apiType = props.cell.optionsApiType || 'GET';
    let params = parseTemplate(props.cell.optionsApiParams,props.cellMap);
    console.log(params,'params____++++');
    const response = await fetch('/api'+props.cell.optionsApiUrl,{
        method:apiType,
        body:params,
        headers:{
            'Content-Type':'application/json'
        }
    }).then(res=>{
        return res.json();
    });
    let data = response[props.cell.optionsApiGetPos]
    const newTree = refactorTreeFields(data, {
        id: 'value',
        name: 'label',
        chiildren: 'children' // 修正拼写
    });
    console.log(data,'data tree');
    state.options = newTree
}
const getOptions = () =>{
    if(props.cell.optionsDataType=='api'){
        getOptsByApi();
    }else if(props.cell.optionsDataType=='static'){
        console.log(props.cell.staticOptsData,'props.cell.staticOptsData')
        const newTree = refactorTreeFields(JSON.parse(props.cell.staticOptsData), {
            id: 'value',
            name: 'label',
            chiildren: 'children' // 修正拼写
        });
        state.options = newTree; 
    }else if(props.cell.optionsDataType=='dict'){
        console.log('字典数据');
    }
}
getOptions();
</script>
<template>
    <el-cascader 
        v-model="props.form[props.cell.__vModel__]"
        :options="state.options" 
        @change="handleChange" 
    />
</template>